package com.bii.gelapp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MarkerGaborActivity2 extends Activity {
	public static final int GALLERY_CHOOSER_INTENT = 1;
	ImageView ivImage;
	public Bitmap originalBmp; // origin
	public Bitmap activeBmp; // edited image
	public static Bitmap colorBmp;
	public Bitmap gaborBmp;
	public Bitmap takenBmp;
	Button btPrev, btSegment, btInverse, btImage;
	TextView tvThreshold, tvLambda, tvSigma;
	SeekBar sbThreshold, sbLambda, sbSigma;

	EditText etSigma;
	EditText etLambda;
	EditText etThreshold;

	int kernelSize = 24;
	double sigma = 0;
	double theta = Math.PI / 2;
	double lambda = 0;
	double gamma = 1;
	double psi = 1.5;

	public static int inverse = 1;
	public static int currentprogress;
	public static int thresholdvalue;
	public static int sigmavalue;
	public static int lambdavalue;

	public static String filepath;
	public static String filetitle = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.markergaboractivity2);
		
		// instructions
		String donotshow = "";
		final Dialog instructiondialog = new Dialog(MarkerGaborActivity2.this);
		instructiondialog.setContentView(R.layout.instructiondialog);
		instructiondialog.setTitle("Attention");
		instructiondialog.setCancelable(true);
		instructiondialog.setCancelable(false);

		TextView tvInstructions = (TextView) instructiondialog
				.findViewById(R.id.tvInstructions);
		ImageView imgView = (ImageView) instructiondialog
				.findViewById(R.id.ivInstructions);
		final CheckBox donotshowbox = (CheckBox) instructiondialog.findViewById(R.id.donotshow);
		Button btOk = (Button) instructiondialog.findViewById(R.id.btOk);

		final SharedPreferences donotshowinstructions = this.getSharedPreferences(
				"instructions", 0);
		donotshow = donotshowinstructions.getString("markergaborinstructions",
				"nothing");
		if (donotshow.equals("nothing")) {
			donotshow = "Show";
		}

		if (donotshow.equals("Show")) {
			tvInstructions.setText("1) Load the marker image with only the marker on it"
					+ "\n2) Move the filter sliders below to only capture the marker fragments"
					+ "\n3) The fragments should be black on a white background, if the image has a black background, click on inverse filter"
					);
			
			Drawable drawable = getResources().getDrawable(R.drawable.markergabor_instruction1);

			Bitmap instructionbmp = ((BitmapDrawable)drawable).getBitmap();
			
			imgView.setImageBitmap(instructionbmp);
			
			instructiondialog.show();

			btOk.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(donotshowbox.isChecked()){
						SharedPreferences.Editor editor = donotshowinstructions.edit();
						editor.putString("markergaborinstructions", "DoNotShow");
						editor.commit();
					}
					else
					{
						SharedPreferences.Editor editor = donotshowinstructions.edit();
						editor.putString("markergaborinstructions", "Show");
						editor.commit();
					}
					instructiondialog.dismiss();
				}
			});
			
		}
		//
		
		
		
		LinearLayout myLayout = (LinearLayout) findViewById(R.id.markergaboractivity2);
		myLayout.requestFocus();
		ivImage = (ImageView) findViewById(R.id.ivImage);
		btPrev = (Button) findViewById(R.id.btPrev);

		btImage = (Button) findViewById(R.id.btImage);
		btImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, GALLERY_CHOOSER_INTENT);
			}
		});

		etSigma = (EditText) findViewById(R.id.etSigma);
		etSigma.setEnabled(false);
		etSigma.setFilters(new InputFilter[] { new InputFilterMinMax("0", "100") });
		etSigma.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				int textLength = etSigma.getText().length();
				etSigma.setSelection(textLength, textLength);
				if (etSigma.getText().toString().equals("")) {
					currentprogress = 0;
				} else {
					currentprogress = Integer.parseInt(etSigma.getText()
							.toString());
				}

				sigmavalue = currentprogress;
				if (currentprogress != 0) {
					sigma = sigmavalue;
					Mat filtermat = new Mat(originalBmp.getHeight(),
							originalBmp.getWidth(), CvType.CV_8U);
					int ch = filtermat.channels();
					Utils.bitmapToMat(originalBmp, filtermat);
					Imgproc.cvtColor(filtermat, filtermat,
							Imgproc.COLOR_BGR2GRAY);

					ch = filtermat.channels();
					// result image below
					Mat resultImg = new Mat();
					// set gabor
					Mat gaborKernel = Imgproc.getGaborKernel(new Size(
							kernelSize, kernelSize), sigma,
							theta/* horizontal */, lambda, gamma, psi,
							CvType.CV_32F);

					ch = filtermat.channels();
					Imgproc.filter2D(filtermat, resultImg, -1, gaborKernel);

					ch = resultImg.channels();

					Bitmap filteredBmp = Bitmap.createBitmap(resultImg.cols(),
							resultImg.rows(), Bitmap.Config.ARGB_8888);
					Utils.matToBitmap(resultImg, filteredBmp);

					gaborBmp = filteredBmp;
					activeBmp = filteredBmp;
					// display result

					ivImage.setImageBitmap(activeBmp);
					// apply gabor before threshold
					// tvSigma.setText("Sigma: " + currentprogress);
					sbSigma.setProgress(sigmavalue);
					// sbThreshold.setEnabled(true);
					// etThreshold.setEnabled(true);
					btInverse.setEnabled(true);
					btSegment.setEnabled(true);

				} else {
					// Bitmap resizedbmp =
					// Bitmap.createScaledBitmap(originalBmp,
					// 300, 300, true);
					ivImage.setImageBitmap(originalBmp);
					sbSigma.setProgress(sigmavalue);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		sbSigma = (SeekBar) findViewById(R.id.sbSigma);
		sbSigma.setEnabled(false);
		sbSigma.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				currentprogress = sbSigma.getProgress();
				sigmavalue = currentprogress;
				if (currentprogress != 0) {
					sigma = sigmavalue;
					Mat filtermat = new Mat(originalBmp.getHeight(),
							originalBmp.getWidth(), CvType.CV_8U);
					int ch = filtermat.channels();
					Utils.bitmapToMat(originalBmp, filtermat);
					Imgproc.cvtColor(filtermat, filtermat,
							Imgproc.COLOR_BGR2GRAY);

					ch = filtermat.channels();
					// result image below
					Mat resultImg = new Mat();
					// set gabor
					Mat gaborKernel = Imgproc.getGaborKernel(new Size(
							kernelSize, kernelSize), sigma,
							theta/* horizontal */, lambda, gamma, psi,
							CvType.CV_32F);

					ch = filtermat.channels();
					Imgproc.filter2D(filtermat, resultImg, -1, gaborKernel);

					ch = resultImg.channels();

					Bitmap filteredBmp = Bitmap.createBitmap(resultImg.cols(),
							resultImg.rows(), Bitmap.Config.ARGB_8888);
					Utils.matToBitmap(resultImg, filteredBmp);

					gaborBmp = filteredBmp;
					activeBmp = filteredBmp;
					// display result
					Bitmap resizedbmp = Bitmap.createScaledBitmap(filteredBmp,
							300, 300, true);
					ivImage.setImageBitmap(resizedbmp);
					// apply gabor before threshold
					etSigma.setText("" + sigmavalue);
					sbThreshold.setEnabled(true);
					etThreshold.setEnabled(true);
					btInverse.setEnabled(true);
					btSegment.setEnabled(true);

				} else {
					ivImage.setImageBitmap(originalBmp);
					sbSigma.setProgress(sigmavalue);
				}
			}
		});

		sbLambda = (SeekBar) findViewById(R.id.sbLambda);
		sbLambda.setEnabled(false);
		sbLambda.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				currentprogress = sbLambda.getProgress();
				lambdavalue = currentprogress;
				if (currentprogress != 0) {
					lambda = lambdavalue;
					Mat filtermat = new Mat(originalBmp.getHeight(),
							originalBmp.getWidth(), CvType.CV_8U);
					int ch = filtermat.channels();
					Utils.bitmapToMat(originalBmp, filtermat);
					Imgproc.cvtColor(filtermat, filtermat,
							Imgproc.COLOR_BGR2GRAY);

					ch = filtermat.channels();
					// result image below
					Mat resultImg = new Mat();
					// set gabor
					Mat gaborKernel = Imgproc.getGaborKernel(new Size(
							kernelSize, kernelSize), sigma,
							theta/* horizontal */, lambda, gamma, psi,
							CvType.CV_32F);

					ch = filtermat.channels();
					Imgproc.filter2D(filtermat, resultImg, -1, gaborKernel);

					ch = resultImg.channels();

					Bitmap filteredBmp = Bitmap.createBitmap(resultImg.cols(),
							resultImg.rows(), Bitmap.Config.ARGB_8888);
					Utils.matToBitmap(resultImg, filteredBmp);

					gaborBmp = filteredBmp;
					activeBmp = filteredBmp;
					// display result
					Bitmap resizedbmp = Bitmap.createScaledBitmap(filteredBmp,
							300, 300, true);
					ivImage.setImageBitmap(resizedbmp);
					// apply gabor before threshold
					etLambda.setText("" + lambdavalue);
					sbThreshold.setEnabled(true);
					etThreshold.setEnabled(true);
					btInverse.setEnabled(true);
					btSegment.setEnabled(true);

				} else {
					ivImage.setImageBitmap(originalBmp);
					etLambda.setText("" + lambdavalue);
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

		});

		etLambda = (EditText) findViewById(R.id.etLambda);
		etLambda.setEnabled(false);
		etLambda.setFilters(new InputFilter[] { new InputFilterMinMax("0",
				"100") });
		etLambda.addTextChangedListener(new TextWatcher() {

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				int textLength = etThreshold.getText().length();
				etThreshold.setSelection(textLength, textLength);
				if (gaborBmp == null) {
					if (takenBmp == null) {
						takenBmp = originalBmp;
					}
				} else {
					// if (takenBmp == null) {
					takenBmp = gaborBmp;
					// }
				}

				int textLength1 = etThreshold.getText().length();
				etThreshold.setSelection(textLength1, textLength1);

				if (etThreshold.getText().toString().equals("")) {
					currentprogress = 0;
				} else {
					currentprogress = Integer.parseInt(etThreshold.getText()
							.toString());
				}

				// currentprogress = sbThreshold.getProgress();
				thresholdvalue = currentprogress;
				if (currentprogress != 0) {
					Mat srcImg = new Mat(takenBmp.getHeight(), takenBmp
							.getWidth(), CvType.CV_8U, new Scalar(4));
					Bitmap myBitmap32 = takenBmp.copy(Bitmap.Config.ARGB_8888,
							true);
					Utils.bitmapToMat(myBitmap32, srcImg);
					Imgproc.cvtColor(srcImg, srcImg, Imgproc.COLOR_BGR2GRAY);
					// Mat thresholdMat = new Mat();
					Mat thresholdMat = new Mat(takenBmp.getHeight(), takenBmp
							.getWidth(), CvType.CV_8U, new Scalar(4));
					if (inverse == 1) {
						Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
								255, Imgproc.THRESH_BINARY_INV);
						inverse = 1;
					} else {
						Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
								255, Imgproc.THRESH_BINARY);
						inverse = 0;
					}
					// invertedThreshold(srcImg,
					// thresholdMat,thresholdvalue,255);
					Bitmap thBmp = Bitmap.createBitmap(thresholdMat.cols(),
							thresholdMat.rows(), Bitmap.Config.ARGB_8888);
					Utils.matToBitmap(thresholdMat, thBmp);
					// Bitmap resizedbmp = Bitmap.createScaledBitmap(thBmp, 300,
					// 300, true);

					ivImage.setImageBitmap(thBmp);
					sbThreshold.setProgress(thresholdvalue);
					activeBmp = thBmp;

					sbThreshold.setEnabled(true);
					etThreshold.setEnabled(true);
					btInverse.setEnabled(true);
					btSegment.setEnabled(true);

				} else {

					ivImage.setImageBitmap(activeBmp);
					sbThreshold.setProgress(thresholdvalue);
				}

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				int textLength = etLambda.getText().length();
				etLambda.setSelection(textLength, textLength);
				if (etLambda.getText().toString().equals("")) {
					currentprogress = 0;
				} else {
					currentprogress = Integer.parseInt(etLambda.getText()
							.toString());
				}

				lambdavalue = currentprogress;
				if (currentprogress != 0) {
					lambda = lambdavalue;
					Mat filtermat = new Mat(originalBmp.getHeight(),
							originalBmp.getWidth(), CvType.CV_8U);
					int ch = filtermat.channels();
					Utils.bitmapToMat(originalBmp, filtermat);
					Imgproc.cvtColor(filtermat, filtermat,
							Imgproc.COLOR_BGR2GRAY);

					ch = filtermat.channels();
					// result image below
					Mat resultImg = new Mat();
					// set gabor
					Mat gaborKernel = Imgproc.getGaborKernel(new Size(
							kernelSize, kernelSize), sigma,
							theta/* horizontal */, lambda, gamma, psi,
							CvType.CV_32F);

					ch = filtermat.channels();
					Imgproc.filter2D(filtermat, resultImg, -1, gaborKernel);

					ch = resultImg.channels();

					Bitmap filteredBmp = Bitmap.createBitmap(resultImg.cols(),
							resultImg.rows(), Bitmap.Config.ARGB_8888);
					Utils.matToBitmap(resultImg, filteredBmp);

					gaborBmp = filteredBmp;
					activeBmp = filteredBmp;
					// display result
					ivImage.setImageBitmap(activeBmp);
					// apply gabor before threshold
					sbLambda.setProgress(lambdavalue);
					sbThreshold.setEnabled(true);
					etThreshold.setEnabled(true);
					btSegment.setEnabled(true);
					btInverse.setEnabled(true);

				} else {
					ivImage.setImageBitmap(originalBmp);
					sbLambda.setProgress(lambdavalue);
				}
			}

		});

		sbThreshold = (SeekBar) findViewById(R.id.sbThreshold);
		sbThreshold.setEnabled(false);
		sbThreshold.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {

				if (gaborBmp == null) {
					if (takenBmp == null) {
						takenBmp = originalBmp;
					}
				} else {
					// if (takenBmp == null) {
					takenBmp = gaborBmp;
					// }
				}

				currentprogress = sbThreshold.getProgress();
				thresholdvalue = currentprogress;
				if (currentprogress != 0) {
					Mat srcImg = new Mat(takenBmp.getHeight(), takenBmp
							.getWidth(), CvType.CV_8U, new Scalar(4));
					Bitmap myBitmap32 = takenBmp.copy(Bitmap.Config.ARGB_8888,
							true);
					Utils.bitmapToMat(myBitmap32, srcImg);
					Imgproc.cvtColor(srcImg, srcImg, Imgproc.COLOR_BGR2GRAY);
					// Mat thresholdMat = new Mat();
					Mat thresholdMat = new Mat(takenBmp.getHeight(), takenBmp
							.getWidth(), CvType.CV_8U, new Scalar(4));
					if (inverse == 1) {
						Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
								255, Imgproc.THRESH_BINARY_INV);
						inverse = 1;
					} else {
						Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
								255, Imgproc.THRESH_BINARY);
						inverse = 0;
					}
					// invertedThreshold(srcImg,
					// thresholdMat,thresholdvalue,255);
					Bitmap thBmp = Bitmap.createBitmap(thresholdMat.cols(),
							thresholdMat.rows(), Bitmap.Config.ARGB_8888);
					Utils.matToBitmap(thresholdMat, thBmp);

					ivImage.setImageBitmap(thBmp);
					// tvThreshold.setText("Threshold: " + currentprogress);
					etThreshold.setText("" + thresholdvalue);
					activeBmp = thBmp;
				} else {
					ivImage.setImageBitmap(gaborBmp);
					// tvThreshold.setText("Threshold: " + currentprogress);
					etThreshold.setText("" + thresholdvalue);
				}
			}
		});

		etThreshold = (EditText) findViewById(R.id.etThreshold);
		etThreshold.setEnabled(false);
		etThreshold.setFilters(new InputFilter[] { new InputFilterMinMax("0",
				"255") });
		etThreshold.addTextChangedListener(new TextWatcher() {

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				int textLength = etThreshold.getText().length();
				etThreshold.setSelection(textLength, textLength);
				if (gaborBmp == null) {
					if (takenBmp == null) {
						takenBmp = originalBmp;
					}
				} else {
					// if (takenBmp == null) {
					takenBmp = gaborBmp;
					// }
				}

				int textLength1 = etThreshold.getText().length();
				etThreshold.setSelection(textLength1, textLength1);

				if (etThreshold.getText().toString().equals("")) {
					currentprogress = 0;
				} else {
					currentprogress = Integer.parseInt(etThreshold.getText()
							.toString());
				}

				// currentprogress = sbThreshold.getProgress();
				thresholdvalue = currentprogress;
				if (currentprogress != 0) {
					Mat srcImg = new Mat(takenBmp.getHeight(), takenBmp
							.getWidth(), CvType.CV_8U, new Scalar(4));
					Bitmap myBitmap32 = takenBmp.copy(Bitmap.Config.ARGB_8888,
							true);
					Utils.bitmapToMat(myBitmap32, srcImg);
					Imgproc.cvtColor(srcImg, srcImg, Imgproc.COLOR_BGR2GRAY);
					// Mat thresholdMat = new Mat();
					Mat thresholdMat = new Mat(takenBmp.getHeight(), takenBmp
							.getWidth(), CvType.CV_8U, new Scalar(4));
					if (inverse == 1) {
						Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
								255, Imgproc.THRESH_BINARY_INV);
						inverse = 1;
					} else {
						Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
								255, Imgproc.THRESH_BINARY);
						inverse = 0;
					}
					// invertedThreshold(srcImg,
					// thresholdMat,thresholdvalue,255);
					Bitmap thBmp = Bitmap.createBitmap(thresholdMat.cols(),
							thresholdMat.rows(), Bitmap.Config.ARGB_8888);
					Utils.matToBitmap(thresholdMat, thBmp);

					ivImage.setImageBitmap(thBmp);
					sbThreshold.setProgress(thresholdvalue);
					activeBmp = thBmp;
				} else {
					ivImage.setImageBitmap(gaborBmp);
					sbThreshold.setProgress(thresholdvalue);
				}
			}

		});

		btInverse = (Button) findViewById(R.id.btInverse);
		btInverse.setEnabled(false);
		btInverse.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (inverse == 1) {
					inverse = 0;

				} else {
					inverse = 1;
				}

				Mat srcImg = new Mat(takenBmp.getHeight(), takenBmp.getWidth(),
						CvType.CV_8U, new Scalar(4));
				Bitmap myBitmap32 = takenBmp
						.copy(Bitmap.Config.ARGB_8888, true);
				Utils.bitmapToMat(myBitmap32, srcImg);
				Imgproc.cvtColor(srcImg, srcImg, Imgproc.COLOR_BGR2GRAY);
				// Mat thresholdMat = new Mat();
				Mat thresholdMat = new Mat(takenBmp.getHeight(), takenBmp
						.getWidth(), CvType.CV_8U, new Scalar(4));
				if (inverse == 1) {
					Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
							255, Imgproc.THRESH_BINARY_INV);
				} else {
					Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
							255, Imgproc.THRESH_BINARY);
				}
				Bitmap thBmp = Bitmap.createBitmap(thresholdMat.cols(),
						thresholdMat.rows(), Bitmap.Config.ARGB_8888);
				Utils.matToBitmap(thresholdMat, thBmp);
				// Bitmap resizedbmp = Bitmap.createScaledBitmap(thBmp, 300,
				// 300,
				// true);

				ivImage.setImageBitmap(thBmp);
				activeBmp = thBmp;

			}
		});
		btSegment = (Button) findViewById(R.id.btSegment);
		btSegment.setEnabled(false);
		btSegment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent goToNextActivity = new Intent(getApplicationContext(),
						MarkerSegmentationActivity.class);
				byte[] bytes;
				if (activeBmp == null) {
					bytes = compressImage(originalBmp);
				} else {
					bytes = compressImage(activeBmp);
				}
				goToNextActivity.putExtra("BMP", bytes);
				startActivity(goToNextActivity);
			}
		});
		// 10 september
		try {
			if (getIntent().hasExtra("imgsrc")) {
				filepath = getIntent().getStringExtra("imgsrc");
				originalBmp = BitmapFactory.decodeFile(filepath);
				colorBmp = BitmapFactory.decodeFile(filepath);
				Mat srcImg = new Mat(originalBmp.getHeight(),
						originalBmp.getWidth(), CvType.CV_8U, new Scalar(4));
				Bitmap myBitmap32 = originalBmp.copy(Bitmap.Config.ARGB_8888,
						true);
				Utils.bitmapToMat(myBitmap32, srcImg);
				Mat grayImg = new Mat();
				Imgproc.cvtColor(srcImg, grayImg, Imgproc.COLOR_BGR2GRAY);
				originalBmp = Bitmap.createBitmap(grayImg.cols(),
						grayImg.rows(), Bitmap.Config.RGB_565);
				Utils.matToBitmap(grayImg, originalBmp);

				activeBmp = originalBmp.copy(Bitmap.Config.RGB_565, true);

				ivImage.setImageBitmap(originalBmp);
				filetitle = getIntent().getStringExtra("mstitle");

				btSegment.setEnabled(true);
				sbSigma.setEnabled(true);
				etSigma.setEnabled(true);
				etLambda.setEnabled(true);
				sbLambda.setEnabled(true);

			}
		} catch (Exception e) {
			//Intent returntoStart = new Intent(this, StartActivity.class);
			Toast.makeText(this.getApplicationContext(), "Image not found at path", Toast.LENGTH_SHORT).show(); 
			btSegment.setEnabled(false);
			btPrev.setEnabled(false);
			btInverse.setEnabled(false);
			btImage.setEnabled(false);
			
	        final Intent intent = new Intent(this, StartActivity.class);        

	        Thread thread = new Thread(){
	           @Override
	           public void run() {
	                try {
	                   Thread.sleep(2000); // As I am using LENGTH_LONG in Toast
	                   intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	                   startActivity(intent); 
               		   finish();
	               } catch (Exception e) {
	                   e.printStackTrace();
	               }
	           } 
	        };

	        thread.start();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == GALLERY_CHOOSER_INTENT) {
			// Get the filepath and display on imageview.

			filepath = getGalleryImagePath(data);
			// Check if the specified image exists.
			// cropImageView.requestLayout();
			if (filepath != null) {
				if (!new File(filepath).exists()) {
					Toast.makeText(this, "Image does not exist.",
							Toast.LENGTH_SHORT).show();
				} else {
					filepath = getGalleryImagePath(data);
					// Check if the specified image exists.
					// ivImage.requestLayout();
					if (filepath != null) {
						if (!new File(filepath).exists()) {
							Toast.makeText(this, "Image does not exist.",
									Toast.LENGTH_SHORT).show();
						} else {
							takenBmp = null;
							Bitmap img = BitmapFactory.decodeFile(filepath);
							originalBmp = BitmapFactory.decodeFile(filepath);
							colorBmp = BitmapFactory.decodeFile(filepath);
							Mat srcImg = new Mat(originalBmp.getHeight(),
									originalBmp.getWidth(), CvType.CV_8U,
									new Scalar(4));
							Bitmap myBitmap32 = originalBmp.copy(
									Bitmap.Config.ARGB_8888, true);
							Utils.bitmapToMat(myBitmap32, srcImg);

							// convert to grayscale
							Mat grayImg = new Mat();
							Imgproc.cvtColor(srcImg, grayImg,
									Imgproc.COLOR_BGR2GRAY);
							originalBmp = Bitmap.createBitmap(grayImg.cols(),
									grayImg.rows(), Bitmap.Config.RGB_565);

							// convert mat back to bitmap set originalBmp
							Utils.matToBitmap(grayImg, originalBmp);
							// set activeBmp
							activeBmp = originalBmp.copy(Bitmap.Config.RGB_565,
									true);

							ivImage.setImageBitmap(activeBmp);
							// allow users to click buttons
							btSegment.setEnabled(true);
							sbSigma.setEnabled(true);
							etSigma.setEnabled(true);
							etLambda.setEnabled(true);
							sbLambda.setEnabled(true);

						}
					}
				}
			}
		}
	}

	public String getGalleryImagePath(Intent data) {
		try {
			Uri imgUri = data.getData();
			String filePath = "";
			if (data.getType() == null) {
				// For getting images from default gallery app.
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(imgUri,
						filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				filePath = cursor.getString(columnIndex);
				cursor.close();
			} else if (data.getType().equals("image/jpeg")
					|| data.getType().equals("image/png")) {
				filePath = imgUri.getPath();
			}
			return filePath;
		} catch (Exception e) {
			return null;
		}

	}

	public byte[] compressImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 0, stream);
		byte[] bytes = stream.toByteArray();
		return bytes;

	}
}
